require([ 'jquery', 'common', 'producttype', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], 
		function($, common, producttype,  validate,timepicker,T_upload) {
	
	//日期控件
	$('#date-start, #date-end').datetimepicker({
		format : "yyyy-mm-dd hh:ii:ss",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minuteStep : 10
	}); 
	
	//日期控件
	$('#dateValue, #dateValueUpt').datetimepicker({
		format : "yyyy-mm-dd",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minView: "month"
	}); 
	
	var addr = new producttype.ProductType({
		wrapper: $('.address-group'),
		firstlevelWrapper: $('#provinceQuery'),
		secondlevelWrapper: $('#cityQuery'),
		thiredlevelWrapper: $('#countyQuery'), 
	});
	
	$('.add').on('click', function() {
		$("#add-product-info").attr("style","display:none;"); 
	});
	
	$("#addProdctSelect").change(function() {
		var opt = $("#addProdctSelect").val(); 
		$.post(ctx+"/product/querybyid", {
			 id:opt
		 },function (data) {
			 var result = data.result;
			 if(result!=null && result=="noauthority") {
				 common.alert1('你无此权限!');
				 return;
			 }
   		 if(data.result!=null && data.result=="againLogin") {
   			 $('.commonConfirm').modal('hide');
   			 common.alert1("登录过期，请重新登录");
				 setTimeout("location.href = ctx + '/login.html'",1000);
            }else{
        		var product = data.product;
        		var imgs = data.imglist;
        		if(imgs!=null && imgs.length>0) {
        			for(var i=0;i<imgs.length;i++) {
        				var img = imgs[i];
        				if(img.type == 1) {
        					console.log("主图地址：" + ctx + img.imgPath);
        					$("#show-product-img").attr("src", ctx + img.imgPath);
        				}
        			} 
        		}
        		if(product != null) {
        			$("#add-product-info").attr("style","display:block;"); 
        			$("#showProductName").html("<b><h4>" + product.productName + "</h4></b>" );
        			$("#showTradeType").html("贸易类型：" + tradeType(product.tradeType));
        			$("#showAttr").html(product.productAttr);
        			$("#showPackType").html("包装：" + product.packType); 
        			$("#showProductType").html("商品类型：" + product.productTypeName); 
        		}else{
        			$("#add-product-info").attr("style","display:none;");
        		}
        	}
        },"json"); 
		
	});
	
	$('#countyQuery').on('click', 'a', function() {
		$("#addshopForm").find("select[name='productId']").html('');
		var thirdroductType = $("#addshopForm").find("input[name='thirdroductType']").val();
		//只查询审核通过的商品
		$.post(ctx+"/product/list", {
			lastType : thirdroductType,
			auditState : 2
		},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		if(data.result!=null && data.result=="againLogin") {
         		$('.commonConfirm').modal('hide');
     			common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else{
        		var datalist = data.productList;
        		var tempHtml = "<option value=''>   </option>";
        		for(var i=0;i<datalist.length;i++){   
                	var data = datalist[i];
                	tempHtml += "<option data-productName=" + data.productName + 
                	"data-packType=" + data.packType + 
                	
                	" value='"+data.id+"'>"+data.productName+"</option>";
                }
      	        $("#addshopForm").find("select[name='productId']").append(tempHtml);
//      	        $("#updateProductForm").find("select[name='freightId']").append(tempHtml); 
          	}
          },"json");
	});
	
	var first_load = true;
	var reload = true; 
	
	$(document).ready(function() {
		showFreight();
	});
	
	//placeholder兼容ie start
	$(function() {
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		
		showProductSupplyByPage(1);
		$("#updateImgIds").val('');
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end

	//清除按钮
	$('.clearBtn').on('click', function() {
		$('.setTableLength').val(10);
		$("#productName").val(''),
		$("#productSn").val(''),
		$("#productCode").val(''),
		$("select[name='auditStatus']").val(''),
		$("select[name='saleStatus']").val(''), 
		$("#date-start").val('');
		$("#date-end").val('');
	});
	
	$(".setTableLength").change(function() {
		reload = true;
		showProductSupplyByPage(1);
	});

	$(".searchBtn").click(function() {
		reload = true;
		showProductSupplyByPage(1);
	});
	
	/*显示所有运费模板s*/
	function showFreight(){
		 $.post(ctx+"/freight/template/list", {},function (data) {
			var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		if(data.result!=null && data.result=="againLogin") {
         		$('.commonConfirm').modal('hide');
     			common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else{
        		var datalist = data.list;
        		var tempHtml = "<option value=''>请选择运费模板</option>";
        		for(var i=0;i<datalist.length;i++){   
                	var data = datalist[i];
                	tempHtml += "<option value='"+data.id+"'>"+data.templateName+"</option>";
                }
      	        $("#addshopForm").find("select[name='freightId']").append(tempHtml);
      	        $("#updateForm").find("select[name='freightId']").append(tempHtml); 
      	        $("#detailForm").find("select[name='freightId']").append(tempHtml); 
          	}
          },"json");
	}
	/*显示所有运费模板e*/
	
	/** 列表查询start **/
	function showProductSupplyByPage(pageNum) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/productsupply/showproductSupplybypage', {	
				pageNum : pageNum,
				pageSize : $('.setTableLength').val() || 10,
				startTime : $("#date-start").val(),
				endTime : $("#date-end").val(),	
				productName : $("#productName").val(),
				productCode : $("#productCode").val(),
				productSn : $("#productSn").val(),
				saleStatus : $("select[name='saleStatus']").val(),
				auditStatus : $("select[name='auditStatus']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
                	var isInterior = $("#isInterior").val();
       				var datapage = data.result;
					var datalist = datapage.result;
					var totalCount = datapage.totalCount;
					var pageNum = datapage.pageNo;
					var pageSize = datapage.pageSize;
					var totalPages = datapage.totalPages;
					$(".totalCount").html(totalCount);
					$(".totalPages").html(totalPages);
					$(".pageNo").html(pageNum);
                    var tempHtml="";   
                    for(var i=0;i<datalist.length;i++){   
                    	var productList = datalist[i];
                    	var specificationList = productList.specificationList;
                    	var no = (pageNum-1)*pageSize+i+1; 
                    	tempHtml +="<tr data-id='"+productList.id+"' data-pageno='" + pageNum + "'>";
                    	tempHtml +="<td>"+no+"</td>";
                    	tempHtml +="<td>"+isnull(productList.productCode)+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.productSn)+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.productName)+"</td>";
                    	tempHtml +="<td>"+isnumber(productList.dateValue)+"</td>";
                    	tempHtml +="<td>总"+specificationList.length+"种</td>"; 
                    	tempHtml +="<td>"+isnull(productList.inventoryQuantity)+"</td>";
                    	tempHtml +="<td>"+isnull(productList.freightTemplateName)+"</td>";  
                    	tempHtml +="<td>"+auditState(productList.auditStatus)+"</td>";
                    	tempHtml +="<td>"+saleStatus(productList.saleStatus)+"</td>";  
                    	tempHtml +="<td>"+common.getSmpFormatDate(productList.createTime)+"</td>";
                    	  
                    	tempHtml +="<td>";
                    	tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-productsupply-detail' data-id=" +productList.id+" class='btn btn-primary btn-xs detail-info'>查看</button>&nbsp";
                		tempHtml +="<button type='button' data-toggle='modal' data-id=" +productList.id+" data-target='.modal-editNews' class='btn btn-warning btn-xs updateproduct'>编辑</button>&nbsp";
                		//内部供应商操作
                    	if(isInterior == 1) {
                    		//销售状态，1销售中，2停售
                    		if(productList.saleStatus == 1){
                        		tempHtml +="<button type='button' data-id="+productList.id+" data-state=2 class='btn btn-danger btn-xs update-saleStatus-btn'>停售</button>&nbsp";
                        	}else if(productList.saleStatus == 2){
                        		tempHtml +="<button type='button' data-id="+productList.id+" data-state=1 class='btn btn-success btn-xs update-saleStatus-btn'>销售</button>&nbsp";
                        	}
                    		//待审核供货
                    		if(productList.auditStatus == 1){ 
                    			tempHtml +="<button type='button' data-toggle='modal' data-target='.modal-audit-product' data-name="+productList.productName+" data-id="+productList.id+" class='btn btn-success btn-xs audit-btn'>审核</button>&nbsp";
                    		}
                    	}
                		
                    	tempHtml +="</td>";
                    	
                    	tempHtml +="</tr>";
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml);
                   
                    if (reload) {
                    	reload = false;
                    	first_load = true;
    					var initPagination = function() {
    						$("#Pagination").pagination(totalCount, {
    							num_edge_entries : 1, // 边缘页数
    							num_display_entries : 4, // 主体页数
    							callback: pageselectCallback,
    							prev_text : "«",
    							next_text : "»",
    							items_per_page : pageSize, 
    							link_to : 'javascript:void(0);'
    						});
    					}();
    					/**分页e**/
                    }
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	function pageselectCallback(page_index, jq) {
		if (first_load) { //第一次初始化不需要请求
			first_load = false;
			return false;
		}
		pageNum = page_index + 1;
		showProductSupplyByPage(pageNum);
	}
	/** 列表查询end **/
	
	
	$(document).on('click', '.audit-btn', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        productName = $this.data('name'),
        pageno = parentTr.data('pageno'); 
        $(".errorMsgAudit").html("");
        $("#auditProductForm").find("input[name='id']").val(id);
        $("#auditProductForm").find("input[name='productName']").val(productName);
        $.getJSON(ctx + '/productsupply/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".errorMsgAudit").html("数据异常,请重试");
    		}else{
    			var product = data.productSupply;
    			var list = data.specificatioList;  
    			var imgList = data.imgList;
    			$("#auditProductForm").find("input[name='id']").val(product.id);  
    			$('#auditProductForm').find("input[name='productName']").val(product.productName);   
    			
    			//贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货
    			//规格报价价格类型以贸易类型区分，海外直邮为包邮含税价格，保税直供包邮不含税  
    			var tradeTypeVal = product.tradeType;
				if(tradeTypeVal == 1) {
					$("#specification-audit-title").html("包邮未含税(单价)");
				}else if(tradeTypeVal == 3) {
					$("#specification-audit-title").html("包邮含税(单价)");
				} 
    			
    			if(list!=null && list.length > 0) {
    				var listHtm = ""; 
    				for(var i=0;i<list.length;i++) {
    					var specificatio = list[i];
    					listHtm += "<tr>";
    					listHtm += "<td><strong>盒</strong><input type='hidden' name='specificationList["+i+"].id' value="+specificatio.id+"></td>";
    					listHtm += "<td><span class='numberAudit"+i+"' >"+specificatio.number+"</span>";
    					listHtm += "<td><span class='unitPrice"+i+"'>"+specificatio.unitPrice+"</span></td>";
    					listHtm += "<td>"+"￥"+"<span>"+(specificatio.number*specificatio.unitPrice).toFixed(2)+"</span></td>";
    					listHtm += "<td><input style='width:70px' class='unitPriceAudit"+i+"' onchange='checkAmountAudit("+i+")' " +
    							"type='text' name='specificationList["+i+"].unitPriceAudit' placeholder='请输入最终销售价' /></td>";
    					listHtm += "<td><span class='unitPriceAuditTotal"+i+"'></span></td>";
    					listHtm += "</tr>";
    					updatelistnum = i;
    				}   
    				$("#specificatio-audit-list-size").val(list.length);
    				$("#specificatio-audit").html(listHtm);
    			} 
    		}
    	});
    }); 
	
	/** 审核通过start **/
	$("#btn_audit_pass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(2); 
	});
	/**  审核通过end **/

	/** 审核不通过start **/
	$("#btn_audit_notpass").click(function() { 
		//审核状态，1待审核，2审核通过，3审核不通过 
		audit(3);
	});
	/**  审核通过end **/
		
	/**
	 * 商品审核
	 */
	function audit(auditState) {
		$('#auditProductForm').find("input[name='auditStatus']").val(auditState);
		$.post(ctx + '/productsupply/audit', $('#auditProductForm').serialize(),
			function(data) {
				if (data.result != null && data.result == "againLogin") {
					$('.commonConfirm').modal('hide');
					common.alert1("登录过期，请重新登录");
					setTimeout( "location.href = ctx + '/login.html'", 1000);
				} else if (data.result == 'success') {
					$(".modal-audit-product").modal('hide');
					common.mySuccessModal2('提交成功');
					showProductSupplyByPage(1);
					$('#auditProductForm').find("#raisePriceType").val("");
					$('#auditProductForm').find("#raisePriceValue").val(""); 
					$('#auditProductForm').find("input[name='auditOpinion']").val("");
					$('#auditProductForm').find("input[name='auditStatus']").val("");
				} else if (data.result == 'fail') {
					$(".errorMsg").html(data.message);
				} else {
					$(".errorMsg").html("信息提交错误");
				}
			}, "json");
	}
	
	$("#auditProductForm").find("#raisePriceType").change(function() {
		$("#auditProductForm").find("#raisePriceValue").val("");
	});
	
	/** 添加验证start **/
	$('#addshopForm').validate({
        rules: {
            'productId': {
                required: true 
            },
            'productSn': {
                required: true 
            },
            'tradeType': {
                required: true
            },
            'netWeight': {
                required: true,
                number: true,
                min:0
            },
            'grossWeight': {
                required: true,
                number: true,
                min:0
            },
            'weight': {
                number: true
            },
            'inventoryQuantity': {
                required: true,
                digits: true,
                number: true
            },
	        'freightId': {
	        	required: true
	        },
	        'saleStatus': {
	        	required: true
	        },
	        'dateValue': {
	        	required: true
	        }
	        
        },
        messages: {
        	'productId': {
     		    required: "请选择分类后选择商品" 
     		 },
     		'productSn': {
                required: "请填写商品货号" 
            },
            'tradeType': {
                required: "请选择贸易类型" 
            }, 
     		'netWeight': {
                required: "请填写净重",
                number: "请输入有效的数字",
                min: "输入必须大于0"
            },
            'grossWeight': {
                required: "请填写毛重",
                number: "请输入有效的数字",
                min: "输入必须大于0"
            },
            'inventoryQuantity': {
            	required: "请填写库存数量",
            	digits: "请输入有效的整数",
            	min : "不能小于0"
            },
            'weight': {
                number: "请输入有效的数字"
            },
     		'price': {
     		    required: "请填写商品积分价格",
     		    digits: "请输入有效的整数",
     		    number: "请输入有效的数字"
     		 },
     		'freightId': {
	        	required: "请选择运费模板"
	        },
	        'saleStatus': {
	        	required: "请选择销售状态"
	        },
	        'dateValue': {
	        	required: "请选择效期"
	        } 
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 添加验证end **/
	
	/** 添加start **/
	$("#btn_addshop").click(function() {
    	var isValid = $("#addshopForm").valid();  
        if (isValid) { 	  
        	 $.post(ctx + '/productsupply/save', $('#addshopForm').serialize(),function (data) {
          		if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		$('.modal-addNews').modal('hide');
             		common.mySuccessModal2(data.message); 
             		showProductSupplyByPage(1); 
 	    			$('#addshopForm').find("input[name='productSn']").val("");
 	    			$('#addshopForm').find("select[name='tradeType']").val(""); 
 	    			$('#addshopForm').find("input[name='netWeight']").val("");
 	    			$('#addshopForm').find("input[name='inventoryQuantity']").val("");
 	    			$('#addshopForm').find("select[name='freightId']").val("");  
 	    			$('#addshopForm').find("select[name='saleStatus']").val(1); 
 	    			$('#addshopForm').find("input[name='customsHsCode']").val(""); 
 	    			$('#addshopForm').find("input[name='customsDeclarationNo']").val(""); 
 	    			$('#addshopForm').find("input[name='customsDeclarationImg']").val("");	//报关单图片地址
 	    			$('#addshopForm').find(".customsDeclarationImg").val("");	//报关单图片
 	    			
 	    			$('#addshopForm').find("input[name='firstProductType']").val(""); 
 	    			$('#addshopForm').find("input[name='secondProductType']").val(""); 
 	    			$('#addshopForm').find("input[name='thirdroductType']").val(""); 
 
               	}else if(data.result=='fail'){
               		common.alert1(data.message); 
               	}else{
               		common.alert1("提交错误");  
               	}
               },"json"); 
        }  
	});
	/** 添加end **/
	
	/** 查看详情start **/
	$(document).on('click', '.detail-info', function (e) { 
        var $this = $(this), 
        id = $this.data('id'); 
    	$.getJSON(ctx + '/productsupply/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".detailMsg").html("数据异常,请重试");
    		}else{
    			var product = data.productSupply;
    			var list = data.specificatioList;  
    			var imgList = data.imgList; 
    			$('#detailForm').find("input[name='productSn']").val(product.productSn);
    			$('#detailForm').find("select[name='tradeType']").val(product.tradeType); 
    			$('#detailForm').find("input[name='netWeight']").val(product.netWeight);
    			$('#detailForm').find("input[name='grossWeight']").val(product.grossWeight); 
    			$('#detailForm').find("input[name='inventoryQuantity']").val(product.inventoryQuantity);
    			$('#detailForm').find("select[name='freightId']").val(product.freightId);  
    			$('#detailForm').find("input[name='customsHsCode']").val(product.customsHsCode); 
    			$('#detailForm').find("input[name='customsDeclarationNo']").val(product.customsDeclarationNo);
    			$('#detailForm').find("input[name='dateValue']").val(product.dateValue);  
    			$("#customsDeclarationImg-detail").attr("src", ctx + product.customsDeclarationImg);	//报关单图片显示
    			
//    			$('#detailForm').find(".customsDeclarationImgUpdate").val("");  
    			console.log(product.productName);
    			$("#detail-ProductName").html("<b><h4>" + product.productName + "</h4></b>" );
    			$("#detail-TradeType").html("贸易类型：" + tradeType(product.tradeType));
    			$("#detail-PackType").html("包装：" + product.packType); 
    			$("#detail-ProductType").html("商品类型：" + product.productTypeName);   
    			if(imgList!= null && imgList.length > 0){
    				$("#detail-product-img").attr("src", ctx + "/" + imgList[0].imgPath);	//商品主图显示 
    			}  
    			 
    			console.log("商品类型：" + product.productTypeName);
    			//贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货
    			//规格报价价格类型以贸易类型区分，海外直邮为包邮含税价格，保税直供包邮不含税  
    			var tradeTypeVal = product.tradeType;
				if(tradeTypeVal == 1) {
					$("#specification-title-detail").html("包邮未含税(单价)");
				}else if(tradeTypeVal == 3) {
					$("#specification-title-detail").html("包邮含税(单价)");
				} 
    			
    			if(list!=null && list.length > 0) {
    				var isInterior = $("#isInterior").val();
    				var listHtm = ""; 
    				for(var i=0;i<list.length;i++) {
    					var specificatio = list[i];
    					listHtm += "<tr class='none_update' >";
    					listHtm += "<td><strong>盒</strong></td>";
    					listHtm += "<td><span>"+ specificatio.number+"</span></td>";
    					listHtm += "<td><span>￥"+specificatio.unitPrice+" </span></td>";
    					listHtm += "<td><span>￥"+(specificatio.number*specificatio.unitPrice).toFixed(2)+"</span></td>";
    					//仅限内部供应商查看销售价/审核价
                    	if(isInterior == 1) {
                    		listHtm += "<td><span style='color:red'>￥"+isnull(specificatio.unitPriceAudit)+"</span></td>"; 
                    		listHtm += "<td><span style='color:red' >￥"+(specificatio.number*specificatio.unitPriceAudit).toFixed(2)+"</span></td>";
                    	}
    					listHtm += "</tr>";
    					updatelistnum = i;
    				}   
    				$("#specificatio-detail").html(listHtm);
    			} 
    		}
    	});
    });
	/** 查看详情end **/
	
	$(document).on('click', '.updateproduct', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        pageno = parentTr.data('pageno');
        $(".errorMsg").html("");
    	$.getJSON(ctx + '/productsupply/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{
    			var product = data.productSupply;
    			var list = data.specificatioList;  
    			var imgList = data.imgList;
    			$("#updateForm").find("input[name='id']").val(product.id);  
    			$('#updateForm').find("input[name='productSn']").val(product.productSn);
    			$('#updateForm').find("select[name='tradeType']").val(product.tradeType); 
    			$('#updateForm').find("input[name='netWeight']").val(product.netWeight);
    			$('#updateForm').find("input[name='grossWeight']").val(product.grossWeight); 
    			$('#updateForm').find("input[name='inventoryQuantity']").val(product.inventoryQuantity);
    			$('#updateForm').find("select[name='freightId']").val(product.freightId);  
    			$('#updateForm').find("input[name='customsHsCode']").val(product.customsHsCode); 
    			$('#updateForm').find("input[name='customsDeclarationNo']").val(product.customsDeclarationNo);
    			$('#updateForm').find("input[name='dateValue']").val(product.dateValue); 
    			$('#updateForm').find("input[name='customsDeclarationImg']").val(product.customsDeclarationImg);	//报关单图片地址
    			$("#customsDeclarationImg-update").attr("src", ctx + product.customsDeclarationImg);	//报关单图片显示
    			
    			$('#updateForm').find(".customsDeclarationImgUpdate").val("");  
    			
    			$("#showProductNameUpdate").html("<b><h4>" + product.productName + "</h4></b>" );
    			$("#showTradeTypeUpdate").html("贸易类型：" + tradeType(product.tradeType));
    			$("#showPackTypeUpdate").html("包装：" + product.packType); 
    			$("#showProductTypeUpdate").html("商品类型：" + product.productTypeName);    
    			if(imgList!= null && imgList.length > 0){
    				$("#show-product-img-update").attr("src", ctx + "/" + imgList[0].imgPath);	//商品主图显示
    			} 
//    			$("#showAttrUpdate").html("属性：" + product.productType);
    			
    			//贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货
    			//规格报价价格类型以贸易类型区分，海外直邮为包邮含税价格，保税直供包邮不含税  
    			var tradeTypeVal = product.tradeType;
				if(tradeTypeVal == 1) {
					$("#specification-title-update").html("包邮未含税(单价)");
				}else if(tradeTypeVal == 3) {
					$("#specification-title-update").html("包邮含税(单价)");
				} 
    			
    			if(list!=null && list.length > 0) {
    				var listHtm = ""; 
    				for(var i=0;i<list.length;i++) {
    					var specificatio = list[i];
    					listHtm += "<tr class='none_update' >";
    					listHtm += "<td><strong>盒</strong></td>";
    					listHtm += "<td><input style='width:45px' class='number"+i+"' name='specificationList["+i+"].number' " +
    							"onchange='checkAmount("+i+")' type='text' value="+specificatio.number+" /></td>";
    					listHtm += "<td><input style='width:45px' class='unitPrice"+i+"' name='specificationList["+i+"].unitPrice' " +
    							"onchange='checkAmount("+i+")' type='text' value="+specificatio.unitPrice+" /></td>";
    					listHtm += "<td><span class=amount"+i+" >"+(specificatio.number*specificatio.unitPrice).toFixed(2)+"</span></td>";
    					listHtm += "<td><a class='btn_del' href='javascript:void(0)'>删除</a></td>";
    					listHtm += "</tr>";
    					updatelistnum = i;
    				}   
    				$("#update-list-num").val(list.length)
    				$("#specificatio-update").html(listHtm);
    			} 
    		}
    	});
    });

	//贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货
	//规格报价价格类型以贸易类型区分，海外直邮为包邮含税价格，保税直供包邮不含税
	$("#addshopForm").find("select[name='tradeType']").change(function() {
		var tradeType = $("#addshopForm").find("select[name='tradeType']").val();
		if(tradeType == 1) {
			$("#specification-title").html("包邮未含税(单价)");
		}else if(tradeType == 3) {
			$("#specification-title").html("包邮含税(单价)");
		}
	});  

	$("#updateForm").find("select[name='tradeType']").change(function() {
		var tradeType = $("#updateForm").find("select[name='tradeType']").val();
		if(tradeType == 1) {
			$("#specification-title-update").html("包邮未含税(单价)");
		}else if(tradeType == 3) {
			$("#specification-title-update").html("包邮含税(单价)");
		}
	}); 
	
	/** 修改start **/
	$("#btn_updateshop").click(function() {
    	var isValid = $("#addshopForm").valid();  
        if (isValid) { 	 
        	 $.post(ctx + '/productsupply/update', $('#updateForm').serialize(),function (data) {
          		if(data.result!=null && data.result=="againLogin"){
 	         		$('.commonConfirm').modal('hide');
 	         		common.alert1("登录过期，请重新登录");
 					setTimeout("location.href = ctx + '/login.html'",1000);
             	}else if(data.result=='success'){
             		$('.modal-editNews').modal('hide');
             		common.mySuccessModal2('提交成功');  
               	}else if(data.result=='fail'){
               		$(".errorMsg").html(data.message);
               	}else{
               		$(".errorMsg").html("信息提交错误");
               	}
               },"json"); 
        }  
	});
	/** 修改end **/
	
	/**删除start */
	$(document).on('click', '.delete-btn', function(){
		var varId = $(this).data("id");
		var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
		$('.commonConfirm').modal('show');				
		common.commonConfirm("删除", "确定删除", "",
			function() {
            	 $.post(ctx+"/product/deleteproductbyid", {
    				 id:varId
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	        showProductSupplyByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 删除end **/
	
	/**销售start */
	$(document).on('click', '.update-saleStatus-btn', function(){
		var varid = $(this).data("id");
        var state = $(this).data('state');
        var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
        if(state == 1){
        	var str = "开始销售";
		}else if(state == 2){
			var str = "停止销售";
		}else{
			var str = "--";
		}
		$('.commonConfirm').modal('show');
		common.commonConfirm("修改", "确定"+str+"该商品吗？", "",
			function() {
            	 $.post(ctx+"/productsupply/updatesalestatus", {
    				 id:varid,saleStatus:state
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	        showProductSupplyByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 销售end **/
	
	/**删除多个s*/
	$('#deleteMany').click(function(e) {
		var ids = "";
		var count = 0;
		var checks = document.getElementsByName("itemCheck");
		console.log(checks);
		for(var i=0;i<checks.length;i++){
			if(checks[i].checked){
				count++;
				ids += checks[i].value + ",";
			}
		}
		if(count<1){
			common.alert1("请至少选择一个");
		}else{
			$('.commonConfirm').modal('show');
			common.commonConfirm("删除", "确定删除", "这"+count+"个商品吗",
				function() {
	            	 $.post(ctx+"/productsupply/deleteproductbyids", {ids:ids},
	            		function (data) {
		            		 var result = data.result;
		     				 if(result!=null && result=="noauthority") {
		     					 common.alert1('你无此权限!');
		     					 return;
		     				 }
	    		    		 if(data.result!=null && data.result=="againLogin") {
	    		    			 $('.commonConfirm').modal('hide');
	    		    			 common.alert1("登录过期，请重新登录");
	    						 setTimeout("location.href = ctx + '/login.html'",1000);
	    		             }else if(data.result=='success'){ 
	    		         		 $(".commonConfirm").modal('hide');
	    		     	         common.mySuccessModal2(data.message);
	    		     	         showProductSupplyByPage(1);
	    		         	}else{
	    		         		$(".updateMsg").html(data.message);
	    		         	}
	    		 },"json"); 
			});
		}
	});
	/**删除多个e*/
	
	/** 修改验证start **/
	$('#updateForm').validate({
        rules: {
            'productId': {
                required: true 
            },
            'productSn': {
                required: true 
            },
            'tradeType': {
                required: true
            },
            'netWeight': {
                required: true,
                digits: true,
                min:0
            },
            'grossWeight': {
                required: true,
                digits: true,
                min:0
            },
            'weight': {
                number: true
            },
            'inventoryQuantity': {
                required: true,
                digits: true,
                number: true
            },
	        'freightId': {
	        	required: true
	        },
	        'saleStatus': {
	        	required: true
	        },
	        'dateValue': {
	        	required: true
	        }
	        
        },
        messages: {
        	'productId': {
     		    required: "请选择分类后选择商品" 
     		 },
     		'productSn': {
                required: "请填写商品货号" 
            },
            'tradeType': {
                required: "请选择贸易类型" 
            }, 
     		'netWeight': {
                required: "请填写净重",
                number: "请输入有效的数字"
            },
            'grossWeight': {
                required: "请填写毛重",
                number: "请输入有效的数字"
            },
            'inventoryQuantity': {
            	required: "请填写库存数量",
            	digits: "请输入有效的整数",
            	min : "不能小于0"
            },
            'weight': {
                number: "请输入有效的数字"
            },
     		'price': {
     		    required: "请填写商品积分价格",
     		    digits: "请输入有效的整数",
     		    number: "请输入有效的数字"
     		 },
     		'freightId': {
	        	required: "请选择运费模板"
	        },
	        'saleStatus': {
	        	required: "请选择销售状态"
	        },
	        'dateValue': {
	        	required: "请选择效期"
	        } 
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 修改验证end **/
	
	//新增供货
	$(".customsDeclarationImg").bind('change', function (e) { 
		imgupload(1);
	});
	
	//修改供货
	$(".customsDeclarationImgUpdate").bind('change', function (e) { 
		imgupload(2);
	});
	
	function imgupload(mark){  
		var formData = new FormData(); 
		if(mark == 1) {
			formData.append('file', $('.customsDeclarationImg')[0].files[0]); //添加图片信息的参数  
		 }else{
			 formData.append('file', $('.customsDeclarationImgUpdate')[0].files[0]); //添加图片信息的参数  
		 }  
		$.ajax({
			 url: ctx + '/productsupply/uploaddeclarationimg',
			 type: 'POST',
			 cache: false, //上传文件不需要缓存
			 data: formData,
			 processData: false, // 告诉jQuery不要去处理发送的数据
			 contentType: false, // 告诉jQuery不要去设置Content-Type请求头
			 success: function (data) {
				 var rs = eval(data); 
				 if(rs.result=="success"){
					 var message = rs.message;
					 console.log("图片地址：" + message);
					 if(mark == 1) {
						 $("#addshopForm").find("input[name='customsDeclarationImg']").val(message);
						 $("#customsDeclarationImgShow").attr("src", ctx + message);
					 }else{
						 $("#customsDeclarationImg-update").attr("src", ctx + message);
						 $("#updateForm").find("input[name='customsDeclarationImg']").val(message);
					 } 
				 }else{
					 alert("图片上传失败");
				 }
			 }, error: function (data) {
				 alert("图片上传失败");
			 } 
		},"json");
	}
	
	function isnull(value) {
		if (value == null || value == '' || typeof (value) == "undefined")
			return "--";
		else
			return value;
	}

	/*销售状态，1销售中，2停售*/
	function saleStatus(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "<span style='color:green'>销售中</span>";
		}else if(value == 2) {
			return "停售";
		} 
	} 
	

	/*贸易类型，1保税直供，2国内发货，3海外直邮，4海外交货*/
	
	function tradeType(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "保税直供";
		}else if(value == 2) {
			return "国内发货";
		} else if(value == 3) {
			return "海外直邮";
		} else if(value == 4) {
			return "海外交货";
		} 
	}
	
	/*审核状态，1待审核，2审核通过，3审核不通过*/
	function auditState(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "<span style='color:red'>待审核</span>";
		}else if(value == 2) {
			return "<span style='color:green'>审核通过</span>";
		} else if(value == 3) {
			return "审核不通过";
		} 
	}
	
	
	
	function isnumber(value) {
		if (value == null || value == '')
			return "0.00";
		else
			return value;
	}

	
});

// 审核时加价
function raisePrice() { 
	var raisePriceValue = $("#raisePriceValue").val();
	var raisePriceType = $("#raisePriceType").val();
	// 规则报价数量
	var size = $("#specificatio-audit-list-size").val(); 
	for (var i = 0; i < size; i++) {
		// 供应商单价
		var unitPrice = $("#auditProductForm").find(".unitPrice" + i).text();
		// 数量
		var number = $("#auditProductForm").find(".numberAudit" + i).text();
		console.log("unitPrice：" + unitPrice + "，number：" + number);
		var auditUnitPrice;
		// 1:按百分比加价，2：按金额数加价
		if (raisePriceType == 1) {
			console.log("按百分比加价...size:" + size);
			// 按加价算出加价后价格
			raisePriceValue = raisePriceValue.replace("%", "");
			auditUnitPrice = unitPrice * (100 + parseFloat(raisePriceValue)) / 100; 
		} else if (raisePriceType == 2) {
			// 按加价算出加价后价格
			auditUnitPrice = parseFloat(unitPrice) + parseFloat(raisePriceValue);
		}
		$("#auditProductForm").find(".unitPriceAudit" + i).val(auditUnitPrice.toFixed(2));
		$(".unitPriceAuditTotal"+i).html("￥"+(number*auditUnitPrice).toFixed(2));
	}
};

